//
//  JSTHomeWebViewController.m
//  KYKJPackDemo
//
//  Created by 罗新 on 2017/9/4.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "JSTHomeWebViewController.h"
#import "JSTAdvertAchieved.h"
#import "JSTStartView.h"
#import "JSTLoadFailView.h"
#import "JSTTableScreenView.h"
#import "MJRefresh.h"
#import "JSTAdWebViewController.h"
#import <WebKit/WebKit.h>

#import "HTLeftUserMenuView.h"
#import "HTLeftMenuView.h"
#import "HTMenuUserModel.h"
#import "KYMineController.h"
#import "KYSettingViewController.h"

@interface JSTHomeWebViewController ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate,HTLeftUserMenuViewDelegate>
//广告刷新定时器
@property (nonatomic, strong) NSTimer *advertIntervalTimer;
//广告刷新时间
@property (nonatomic, assign) NSInteger advertIntervalTime;
//提醒框
@property (nonatomic, weak) CustomAlertView *alertView;
//状态栏
@property (nonatomic, strong) UIView *statusView;
//主网页
@property (nonatomic, strong) WKWebView *webview;
//进度条
@property (nonatomic, strong) UIProgressView *progressView;
//插屏广告
@property (nonatomic, weak) JSTTableScreenView *tableScreenView;
//插屏背景图片
@property (nonatomic, weak) UIView *bgView;
//插屏关闭图片
@property (nonatomic, weak) UIImageView *closeImg;
//插屏关闭按钮
@property (nonatomic, weak) UIButton *closeBtn;
//开屏广告
@property (nonatomic, weak) JSTStartView *startView;
//上次打开的链接
@property (nonatomic, copy) NSString *lastUrl;
//开屏加载完成
@property (nonatomic, assign) BOOL startViewOpenSuccess;
//插屏广告加载完成
@property (nonatomic, assign) BOOL screenViewOpenSuccess;
//当前加载的链接
@property (nonatomic, strong) NSString *currentUrl;
//当前加载的标题
@property (nonatomic, strong) NSString *currentTitle;
//阅读模块
@property (nonatomic, strong) DataWebViewModel *model;
//广告位悬停id数组
@property (nonatomic, strong) NSMutableArray *adsIdArr;
//当前页广告悬停时间字典
@property (nonatomic, strong) NSMutableDictionary *adstopTimeDict;

@property (nonatomic, weak) HTLeftUserMenuView *userMenu;

@property (nonatomic, strong) HTLeftMenuView *menu;

@end

@implementation JSTHomeWebViewController
#pragma mark - singleton
+ (JSTHomeWebViewController *)shareHomeVC {
    static JSTHomeWebViewController *homeVC = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        homeVC = [[JSTHomeWebViewController alloc] init];
    });
    return homeVC;
}
#pragma mark - life cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.frame = [UIScreen mainScreen].bounds;
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 0.创建横竖屏监听
    [self createNotification];
    if ([JSTSystemInfo isOpenHistory]) {
        [self createLastOpenUrl];
    }
    // 1.创建侧滑
//    if ([JSTSystemInfo isOpenSileMenu]) {
        [self setUpLefeMenuView];
//    }
//    if (![JSTSystemInfo isOpenTabbar]) {
        self.tabBarController.tabBar.hidden = YES;
//    }
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent animated:YES];
    [self.navigationController setNavigationBarHidden:YES animated:animated];
    // 即将进入视图 开启定时器 定时刷新广告
    if (self.advertIntervalTimer) [self.advertIntervalTimer setFireDate:[NSDate distantPast]];
    //加载网页
    [self createBaseView];
    //加载开屏广告
    [self createStartView];
    //加载插屏广告
    [self createTableScreenView];
    
    // 刷新侧滑栏数据(更新数据后的重新展示)
//    if ([JSTSystemInfo isOpenSileMenu]) {
        [self.userMenu updateHeaderInfo];
//    }
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    self.tabBarController.hidesBottomBarWhenPushed = YES;
    [self.navigationController setNavigationBarHidden:NO animated:animated];
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleDefault animated:YES];
    // 即将离开试图 暂停定时器 防止无效统计
    if (self.advertIntervalTimer) [self.advertIntervalTimer setFireDate:[NSDate distantFuture]];
}

/**
 *  创建侧滑
 */
- (void)setUpLefeMenuView
{
    HTLeftUserMenuView *userMenu = [[HTLeftUserMenuView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width * 0.8, [UIScreen mainScreen].bounds.size.height)];
    userMenu.delegate = self;
    self.userMenu = userMenu;
    
    self.menu = [[HTLeftMenuView alloc] initWithDependencyView:self.view MenuView:userMenu isShowCoverView:YES];
}

#pragma mark - HTLeftUserMenuViewDelegate
- (void)leftUserMenuFooterViewDidClickBtnWithType:(HTMenuFooterBtnType)type
{
    switch (type) {
        case HTMenuFooterBtnSettingType:
            [self jumpToSetingVc];
            break;
            
        case HTMenuFooterBtnCollectType:
            [self collectCurrentHtml];
        default:
            break;
    }
}

- (void)jumpToSetingVc
{
    // 0.首先隐藏界面
    [self.menu hidenWithAnimation];

    // 1.跳转
    KYSettingViewController *settingVc = [[KYSettingViewController alloc] init];
    [self.navigationController pushViewController:settingVc animated:YES];
}

- (void)collectCurrentHtml
{
    // 0.当前价在html
    NSString *html = [JSTSystemInfo webUrl];

    
#warning - NO(利用sql存储收藏&动态界面)
    // 1.存储方式
    [MBProgressHUD showSuccess:NSLocalizedString(@"收藏成功...", nil)];
}

- (void)leftUserMenuViewClick:(NSInteger)tag model:(HTMenuUserModel *)model {
    [self.menu hidenWithAnimation];
    
    if (model.linkUrlStr) {
        [self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:model.linkUrlStr]]];
    }
}

- (void)leftUserMenuHeaderViewDidClickBgView {
    // 0.首先隐藏界面
    [self.menu hidenWithAnimation];
    
    // 1.判断是否登录没有
    if ([KYUserAccountTool shareUserData].token) { // 已登录
        KYMineController *mineVc = [[KYMineController alloc] init];
        [self.navigationController pushViewController:mineVc animated:YES];
        
    } else { // 未登录
        KYLoginController *loginVc = [[KYLoginController alloc] init];
        KYNavigationController *nav = [[KYNavigationController alloc] initWithRootViewController:loginVc];
        [self presentViewController:nav animated:YES completion:nil];
    }
}

#pragma mark - notification
/**
 横竖屏监听
 */
- (void) createNotification {
    [[UIDevice currentDevice] beginGeneratingDeviceOrientationNotifications];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(deviceOrientationDidChange) name:UIDeviceOrientationDidChangeNotification object:nil];
}
/**
 实现横竖屏监听方法
 */
- (void)deviceOrientationDidChange {
    if([UIDevice currentDevice].orientation == UIDeviceOrientationPortrait) {
        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationPortrait];
    } else if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeLeft) {
        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeRight];
    }else if ([UIDevice currentDevice].orientation == UIDeviceOrientationLandscapeRight){
        [[UIApplication sharedApplication] setStatusBarOrientation:UIInterfaceOrientationLandscapeLeft];
    }
    [self createBaseView];
}

#pragma mark - 创建各类视图
/**
 创建主视图
 */
- (void) createBaseView {
    [self.view addSubview:self.statusView];
    [self.view addSubview:self.webview];
    [self.view addSubview:self.progressView];
    //判断是否横屏状态，及时调整
    if (kDeviceWidth > kDeviceHeight) {
        CGFloat screenViewY = kRealLandscapeScreenHeight(85);
        CGFloat screenViewW = kDeviceHeight - kRealLandscapeScreenWidth(40);
        CGFloat screenViewH = screenViewW/6.*5.;
        CGFloat screenViewX = (kDeviceWidth - screenViewW)/2;
        CGFloat imgViewX = screenViewX + screenViewW - kRealLandscapeScreenHeight(30);
        CGFloat imgViewY = kRealLandscapeScreenHeight(20);
        self.tableScreenView.frame = CGRectMake(screenViewX, screenViewY, screenViewW,screenViewH);
        self.closeImg.frame = CGRectMake(imgViewX, imgViewY, kRealLandscapeScreenHeight(30), kRealLandscapeScreenHeight(65));
        self.closeBtn.frame = CGRectMake(imgViewX, imgViewY, kRealLandscapeScreenHeight(30), kRealLandscapeScreenHeight(30));
        self.webview.frame = CGRectMake(0, 20, kDeviceWidth, kNavViewHight);
        self.statusView.frame = CGRectMake(0, 0, kDeviceWidth, 20);
    }else{
        CGFloat screenViewX = kRealScreenWidth(20);
        CGFloat screenViewW = kDeviceWidth - kRealScreenWidth(40);
        CGFloat screenViewH = screenViewW/6.*5.;
        CGFloat screenViewY = (kDeviceHeight - screenViewH)/2;
        CGFloat imgViewX = kDeviceWidth-kRealScreenWidth(50);
        CGFloat imgViewY = screenViewY - kRealScreenWidth(65);
        self.tableScreenView.frame = CGRectMake(screenViewX, screenViewY, screenViewW,screenViewH);
        self.closeImg.frame = CGRectMake(imgViewX, imgViewY, kRealScreenWidth(30), kRealScreenWidth(65));
        self.closeBtn.frame = CGRectMake(imgViewX, imgViewY, kRealScreenWidth(30), kRealScreenWidth(30));
        self.webview.frame = CGRectMake(0, 20, kDeviceWidth, kNavViewHight);
        self.statusView.frame = CGRectMake(0, 0, kDeviceWidth, 20);
    }
}

/**
 创建回到上次打开连接提示
 */
- (void) createLastOpenUrl{
    if (!IsStrEmpty([JSTSystemInfo lastUrl]) && ![[JSTSystemInfo lastUrl] isEqualToString:[JSTSystemInfo webUrl]]) {
        self.lastUrl = [JSTSystemInfo lastUrl];
        [JSTServer showAlertWithTitle:@"" withDetailStr:@"是否打开上次关闭前打开的地址" andConfirmAction:^{
            [self.webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.lastUrl]]];
        }];
    }
}

/**
 创建开屏广告
 */
- (void) createStartView {
    if(self.startViewOpenSuccess) return;
    JSTStartView *startView = [[JSTStartView alloc] init];
    self.startView = startView;
    [self.view addSubview:startView];
    [self.startView createContent:kHomePageModel end:^{
        self.startViewOpenSuccess = YES;
        if (((AppDelegate *)[[UIApplication sharedApplication] delegate]).pushDict) {
            NSDictionary *pushDict = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).pushDict;
            if (IsStrEmpty(pushDict[@"link"])) return;
            JSTAdWebViewController *pushVC = [[JSTAdWebViewController alloc] init];
            pushVC.pushData = pushDict;
            pushVC.urlStr = pushDict[@"link"];
            pushVC.adViewShowComplict = ^(){
                [self createTableScreenView];
            };
            UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:pushVC];
            [self presentViewController:nav animated:YES completion:nil];
        }else{
            [self createTableScreenView];
        }
    } changePage:^{
        self.startViewOpenSuccess = YES;
    }];
}
/**
 创建横屏广告
 */
- (void) createTableScreenView {
    if (self.screenViewOpenSuccess) return;
    if (!self.startViewOpenSuccess) return;
    UIWindow *window = ((AppDelegate *)[[UIApplication sharedApplication] delegate]).window;
    //背景View
    UIView *bgView = [[UIView alloc] initWithFrame:window.bounds];
    bgView.backgroundColor = [UIColor colorWithRed:33/255 green:33/255 blue:33/255 alpha:0.7];
    [window addSubview:bgView];
    //创建关闭按钮
    UIImageView *closeImg = [[UIImageView alloc] init];
    closeImg.image = [UIImage imageNamed:@"screen_close"];
    UIButton *closeBtn = [[UIButton alloc] init];
    [closeBtn addTarget:self action:@selector(closeScreenButtonClick) forControlEvents:UIControlEventTouchUpInside];
    JSTTableScreenView *screenView = [[JSTTableScreenView alloc] init];
    self.tableScreenView = screenView;
    if (kDeviceWidth > kDeviceHeight) {
        CGFloat screenViewY = kRealScreenHeight(90);
        CGFloat screenViewH = (kDeviceHeight - screenViewY)/2;
        CGFloat screenViewW = screenViewH/5.*6.;
        CGFloat screenViewX = (kDeviceWidth - screenViewW)/2;
        CGFloat imgViewX = kDeviceWidth-kRealScreenHeight(73);
        CGFloat imgViewY = screenViewY - kRealScreenHeight(65);
        self.tableScreenView.frame = CGRectMake(screenViewX, screenViewY, screenViewW,screenViewH);
        closeImg.frame = CGRectMake(imgViewX, imgViewY, kRealScreenWidth(30), kRealScreenWidth(65));
        closeBtn.frame = CGRectMake(imgViewX, imgViewY, kRealScreenWidth(30), kRealScreenWidth(30));
    }else {
        CGFloat screenViewX = kRealScreenWidth(20);
        CGFloat screenViewW = kDeviceWidth - kRealScreenWidth(40);
        CGFloat screenViewH = screenViewW/6.*5.;
        CGFloat screenViewY = (kDeviceHeight - screenViewH)/2;
        CGFloat imgViewX = kDeviceWidth-kRealScreenWidth(50);
        CGFloat imgViewY = screenViewY - kRealScreenWidth(65);
        self.tableScreenView.frame = CGRectMake(screenViewX, screenViewY, screenViewW,screenViewH);
        closeImg.frame = CGRectMake(imgViewX, imgViewY, kRealScreenWidth(30), kRealScreenWidth(65));
        closeBtn.frame = CGRectMake(imgViewX, imgViewY, kRealScreenWidth(30), kRealScreenWidth(30));
    }
    kHomePageModel.delegate = self;
    [bgView addSubview:closeImg];
    [bgView addSubview:self.tableScreenView];
    [bgView addSubview:closeBtn];
    self.closeImg = closeImg;
    self.closeBtn = closeBtn;
    self.bgView = bgView;
    self.tableScreenView.layer.cornerRadius = 5.;
    self.tableScreenView.layer.masksToBounds = YES;
    [self.tableScreenView createContent:kHomePageModel removeView:^{
        [self closeScreenButtonClick];
    }];
}

/**
 点击插屏关闭按钮
 */
- (void)closeScreenButtonClick{
    self.screenViewOpenSuccess = YES;
    [JSTNotification createNotification];
    [self.bgView removeFromSuperview];
}

#pragma mark - wkwebViewDelegate
// 页面开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    if (self.advertIntervalTimer) {
        [self.advertIntervalTimer invalidate];
        self.advertIntervalTimer = nil;
        self.advertIntervalTime = 0;
    }
    //添加定时器刷新功能
    self.advertIntervalTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(advertInvterval) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.advertIntervalTimer forMode:NSDefaultRunLoopMode];
    if (!IsArrEmpty(self.adstopTimeDict)) {
        for (NSDictionary *dic in [self.adstopTimeDict allValues]) [JSTServer postAdvertMonitorStopTime:dic success:nil err:nil];
        [self.adstopTimeDict removeAllObjects];
        [self.adsIdArr removeAllObjects];
    }
}

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation{
}
// 页面加载完成之后调用
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    //停止刷新
    [self.webview.scrollView headerEndRefreshing];
    //存储当前模型
    JSTCacheModel *model = [[JSTCacheModel alloc] init];
    model.url = self.currentUrl;
    [self.webview evaluateJavaScript:@"document.title" completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        model.title = [NSString stringWithFormat:@"%@",result];
        [JSTFMDBManager insertOrUpdateModelToDatabase:model];
    }];
    [self loadReader];
}
// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation{
    [self.webview.scrollView headerEndRefreshing];
    //加载失败提示页
    JSTLoadFailView *failView = [[JSTLoadFailView alloc] init];
    [self.view addSubview:failView];
    [failView createContent:^{
        [self.webview reload];
        [failView removeFromSuperview];
    }];
}

// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
}
// 在收到响应后，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    decisionHandler(WKNavigationResponsePolicyAllow);
}
// 在发送请求之前，决定是否跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    NSString *originUrlString = navigationAction.request.URL.absoluteString;
    self.currentUrl = originUrlString;
    decisionHandler(WKNavigationActionPolicyAllow);
}
//OC在JS调用方法做的处理
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
    if ([message.name isEqualToString:@"adParams"]) {
        NSArray *param = message.body;
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        dic[@"url"] = [NSString stringWithFormat:@"%@",param[0]];
        dic[@"adid"] = [NSString stringWithFormat:@"%@",param[1]];
        dic[@"typeId"] = [NSString stringWithFormat:@"%@",param[2]];
        dic[@"status"] = [NSString stringWithFormat:@"%@",param[3]];
        dic[@"apkurl"] = [NSString stringWithFormat:@"%@",param[4]];
        dic[@"c2_Url"] = [NSString stringWithFormat:@"%@",param[5]];
        dic[@"zoneId"] = [NSString stringWithFormat:@"%@",param[6]];
        kHomePageModel.delegate = self;
        [kHomePageModel createWebViewAdvertOclick:dic];
    }else if ([message.name isEqualToString:@"uploadPv"]){
        NSArray *param = message.body;
        NSMutableDictionary *dict = [NSMutableDictionary dictionary];
        dict[@"event"] = @"view";
        [JSTServer requestPostStatisticsData:dict postInterface:[NSString stringWithFormat:@"%@",param[4]] dataDic:nil errorStr:nil];
    }else if ([message.name isEqualToString:@"adMonitor"]){
        NSString *asdid = [NSString stringWithFormat:@"%@",message.body];
        NSMutableDictionary *paramDic = [NSMutableDictionary dictionary];
        paramDic[@"asdid"] = asdid;
        paramDic[@"url"] = self.currentUrl;
        paramDic[@"urltitle"] = self.currentTitle;
        paramDic[@"stoptime"] = @"1";
        if ([self.adsIdArr containsObject:asdid]) {
            NSDictionary *dic = [self.adstopTimeDict valueForKey:asdid];
            NSString *oldtime =[NSString stringWithFormat:@"%@",dic[@"stoptime"]];
            NSInteger newTime = oldtime.integerValue + 1;
            [dic setValue:[NSString stringWithFormat:@"%ld",(long)newTime] forKey:@"stoptime"];
            [self.adstopTimeDict setObject:dic forKey:asdid];
        }else{
            [self.adsIdArr addObject:asdid];
            [self.adstopTimeDict setObject:paramDic forKey:asdid];
        }
    }
}
//WKScriptMessageHandler协议方法
/**
 加载阅读器
 */
- (void) loadReader{
    NSString *str = [NSString stringWithFormat:@"function textContent(){return document.getElementById(\"%@\").innerText;}textContent()", [JSTSystemInfo readerText]];
    [self.webview evaluateJavaScript:str completionHandler:^(NSString * _Nullable result, NSError * _Nullable error) {
        if (!IsStrEmpty(result)) {
            [self presentViewController:kPublicReadCtl animated:NO completion:nil];
            [self createReadData:self.currentUrl otherUrl:nil leftContent:nil currentContent:nil rightContent:nil];
            [self.webview goBack];
            return;
        }
    }];
    [self loadWebAdvert];
    if ([[JSTSystemInfo shareType] isEqualToString:@"3"]) {
        [self shareInput];
    }
    self.advertIntervalTimer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(advertInvterval) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.advertIntervalTimer forMode:NSDefaultRunLoopMode];
}
// 判断是否包含分享按钮
- (void) shareInput {
//    [self.webview stringByEvaluatingJavaScriptFromString:
//     @"var share = document.getElementById('shareForUnion');"
//     "share.onclick = function(){"
//     "share.value='123';"
//     "window.location.href = \"jst://shareForUnion?a=b\";"
//     "}"
//     ];
}

- (void)createReadData:(NSString *)url otherUrl:(NSString *)otherUrl  leftContent:(NSString *)leftContent currentContent:(NSString *)currentContent rightContent:(NSString *)rightContent {
    self.model = [[DataWebViewModel alloc] init];
    self.model.dataWebUrl = url;
    self.model.leftDataStr = leftContent;
    self.model.currentDataStr = currentContent;
    self.model.rightDataStr = rightContent;
    self.model.otherUrl = otherUrl;
    [self.view addSubview:self.model.dataWebView];
    [self.model.dataWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:url]]];
}
- (void) advertInvterval{
    self.advertIntervalTime ++;
    if (self.advertIntervalTime == [JSTSystemInfo advertInterval]) {
        self.advertIntervalTime = 0;
        [self loadWebAdvert];
    }
}

// 广告跳转
- (void) changePage:(NSString *)url dataDic:(NSDictionary *)dic {
    JSTAdWebViewController *webView = [[JSTAdWebViewController alloc] init];
    webView.pushData = dic;
    webView.urlStr = url;
    webView.zoneId = dic[@"zoneId"];
    NSString *typeId = [NSString stringWithFormat:@"%@", [dic valueForKey:@"typeid"]];
    if ([typeId isEqualToString:@"1000"]) {
        webView.adViewShowComplict = ^{
            [self createTableScreenView];
        };
    }
    [self.navigationController pushViewController:webView animated:YES];
}

//添加悬浮监听
- (void)addAdvertStopTime:(NSString *)divId{
   NSString *stopTimePath = [[NSBundle mainBundle] pathForResource:@"jstAdvertStopTime" ofType:@"txt"];
    NSString *stopTimeStr = [NSString stringWithContentsOfFile:stopTimePath encoding:NSUTF8StringEncoding error:nil];
    NSString *stopTimeJS = [NSString stringWithFormat:stopTimeStr,divId,divId,divId,divId,divId];
    [self.webview evaluateJavaScript:stopTimeJS completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        
    }];
}

// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
    if (object == self.webview && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        if (newprogress == 1) {
            [self.progressView setProgress:1 animated:YES];
            [UIView animateWithDuration: 0.5 animations:^{
                self.progressView.alpha = 0.0;
            }completion:^(BOOL finished) {
                [self.progressView setProgress:0.0 animated:NO];
            }];
        }else {
            self.progressView.alpha = 1.0;
            [self.progressView setProgress:newprogress animated:YES];
        }
    } else if (object == self.webview &&[keyPath isEqualToString:@"title"]) {
        self.currentTitle = self.webview.title;
    }
}

#pragma mark 加载广告
- (void) loadWebAdvert{
    NSString *getAllDivJS = [NSString stringWithFormat:@
                             "function getPageDivIds(){"
                             "var divIds=new Array();"
                             "var divs = document.getElementsByTagName('div');"
                             "for(var markNum = 0; markNum < divs.length; markNum++){"
                             "if (divs[markNum].id !== null && divs[markNum].id !== undefined && divs[markNum].id !== '') {"
                             "divIds[markNum] = divs[markNum].id;"
                             "}"
                             "}"
                             "return divIds.join("");"
                             "};"
                             "getPageDivIds();"];
    //遍历出当前html所有不为空的div ID
    [self.webview evaluateJavaScript:getAllDivJS completionHandler:^(id _Nullable result, NSError * _Nullable error) {
        NSString *divIdStr = [NSString stringWithFormat:@"%@",result];
        //广告位id数组
        NSArray *divIdArr = [divIdStr componentsSeparatedByString:@","];
        //判断有无对应div ID 的广告位ID
        NSUserDefaults *userDf = [NSUserDefaults standardUserDefaults];
        NSArray *advertIdData = (NSArray *)[userDf valueForKey:@"adidDic"];
        for (int j = 0; j < advertIdData.count; j++) {
            for (int i = 0; i < divIdArr.count; i++) {
                NSString *divId = [NSString stringWithFormat:@"%@", divIdArr[i]];
                if ([advertIdData[j] isEqualToString:divId]) {
                    JSTAdvertAchieved *advertAchieved = [[JSTAdvertAchieved alloc] init];
                    //加载广告
                    [advertAchieved getAdvertId:divId jsStr:^(NSString *jsStr) {
                        [self.webview evaluateJavaScript:jsStr completionHandler:nil];
                    }];
                    //添加监听
                    [self addAdvertStopTime:divId];
                }
            }
        }
    }];
}

/**
 扫描二维码按钮
 */
#warning 需要修改交互方法
- (void) qrScanInput
{
    if ([JSTSystemInfo qrScanIsOpen]) {
        NSString *qrscanStr = [NSString stringWithFormat:@"var qr = document.getElementById('%@');"
                               "qr.onclick=function(){"
                               "window.jsObj.scanQRCode(); };",[JSTSystemInfo qrScanId]];
        [self.webview evaluateJavaScript:qrscanStr completionHandler:nil];
    }
    
}

#pragma mark - Lazy load
- (WKWebView *)webview{
    if (!_webview) {
        _webview = [[WKWebView alloc] init];
        _webview.frame = CGRectMake(0, 20, kDeviceWidth, kNavViewHight);
        _webview.backgroundColor = [UIColor redColor];
        _webview.navigationDelegate = self;
        _webview.allowsBackForwardNavigationGestures = YES;
        [_webview loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:[JSTSystemInfo webUrl]]]];
        _webview.scrollView.showsVerticalScrollIndicator = NO;
        [[_webview configuration].userContentController addScriptMessageHandler:self name:@"adParams"];
        [[_webview configuration].userContentController addScriptMessageHandler:self name:@"uploadPv"];
        [[_webview configuration].userContentController addScriptMessageHandler:self name:@"adMonitor"];
        [_webview addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:nil];
        [_webview addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
        [_webview.scrollView addHeaderWithTarget:_webview action:@selector(reload)];
    }
    return _webview;
}

- (UIProgressView *)progressView{
    if (!_progressView) {
        _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, 20, kDeviceWidth, 0)];
        _progressView.tintColor = [UIColor greenColor];;
        _progressView.trackTintColor = [UIColor whiteColor];
    }
    return _progressView;
}
- (UIView *)statusView
{
    if (!_statusView) {
        _statusView.frame = CGRectMake(0, 0, kDeviceWidth, 20);
        _statusView = [[UIView alloc] init];
        _statusView.backgroundColor = [JSTSystemInfo backStatusColor];
    }
    return _statusView;
}
-(NSMutableArray *)adsIdArr{
    if (!_adsIdArr) {
        _adsIdArr = [NSMutableArray array];
    }
    return _adsIdArr;
}

- (NSMutableDictionary *)adstopTimeDict{
    if (!_adstopTimeDict) {
        _adstopTimeDict = [NSMutableDictionary dictionary];
    }
    return _adstopTimeDict;
}
@end
